﻿using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace LEE.Tools.Others
{
    public class NetworkHelper
    {
        /// <summary>
        /// 检查IP是否在线
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static bool CheckIpOnline(string ipAddress, int timeout = 120)
        {
            var online = false; //是否在线
            try
            {
                var ping = new Ping();
                var pingReply = ping.Send(ipAddress, timeout: timeout);
                if (pingReply != null) online = pingReply.Status == IPStatus.Success;
            }
            catch
            {
                return false;
            }
            return online;
        }

        /// <summary>
        /// 识别urlStr是否是网络路径
        /// </summary>
        /// <param name="urlStr"></param>
        /// <returns></returns>
        public static bool UrlDiscern(string urlStr)
        {
            if (Regex.IsMatch(urlStr, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
